`timescale 1ns/1ps
module delay_pulse_top;
    reg reset,clk,trigger;
    reg [3:0]n;
    wire pulse;

    always # 1 clk = ~clk;
    initial begin
        reset = 0;
        clk = 0;
        n=2;
        trigger = 0;
        # 2 reset =1;
        # 2 reset =0;
        # 4 trigger = 1;
        # 5 trigger = 0; 
        # 9 n=5;
        # 4 trigger = 1;
        # 5 trigger = 0;
        # 20 $stop;
    end
    dealy_pulse dp(pulse,n,trigger,reset,clk);
	initial
	begin
    	$dumpfile("test.vcd");
    	$dumpvars(0, dp);
 	end
endmodule

module dealy_pulse(pulse,n,trigger,reset,clk);
	input trigger,reset,clk;
    input [3:0]n;
    output pulse;
    
    reg [4:0]count;
    reg D1; //to store temp trigger.
    wire flag;//posege of trigger
    reg [3:0] n_tmp;
    wire [3:0] n_tmp2;
    
    assign n_tmp2= n_tmp+5'd1;
    
    assign pulse = (n_tmp2 == count)?1:0;

    assign flag=(trigger==1&D1==0)?1:0;
    
    always @(posedge clk or posedge reset)
        if(reset)
            D1 <=0;
        else 
            D1 <= trigger;
  
    always @(posedge clk or posedge reset)
        if(reset)begin
            count <=5'h0;
            n_tmp <=4'h0;
        end
        else if( flag ==1)begin
            count <= 5'd1;  
            n_tmp <= n;
        end
        else if(count != 5'h0 & count != n_tmp2+1)
            count <= count+5'd1;
        else if(count==n_tmp2+1)
            count <= count;
        
endmodule
